package com.youxin.chat.user.mq.consumer.message;

import com.alibaba.fastjson.JSONObject;

import com.youxin.base.MsgDto;
import com.youxin.common.constant.MsgTypeEnum;
import com.youxin.chat.user.manager.ImManager;
import com.youxin.chat.user.mapper.UserInfoMapper;
import com.youxin.chat.user.model.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Service
public class QuitGroupMsgResolver implements MsgResolver {

    private Logger logger = LoggerFactory.getLogger(QuitGroupMsgResolver.class);

    @Resource
    private ImManager imManager;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Override
    public Boolean supportType(String type) {
        return MsgTypeEnum.QUIT_GROUP.getType().equalsIgnoreCase(type);
    }

    @Override
    public void doResolve(MsgDto msgDto) {
        logger.info("处理退出群组通知，data={}", JSONObject.toJSONString(msgDto));
        try {
            JSONObject jsonObject = JSONObject.parseObject(msgDto.getData());
            String userNo = jsonObject.getString("userNo");
            String groupNo = jsonObject.getString("groupNo");
            Map<String, Object> dataMap = new HashMap<>();
            UserInfo userInfo = userInfoMapper.selectByUserNo(userNo);
            dataMap.put("operatorNickname", Optional.ofNullable(userInfo.getNickName()).orElse(""));
            dataMap.put("targetUserIds", Arrays.asList(userInfo.getUserNo()));
            dataMap.put("targetUserDisplayNames", Arrays.asList(Optional.ofNullable(userInfo.getNickName()).orElse("")));
            String msg = "退出群成员";
            imManager.sendGroupMsg("Quit", imManager.getSystemNo(), Arrays.asList(groupNo), userNo, JSONObject.toJSONString(dataMap), msg);
            logger.info("处理退出群组通知完成，data={}", JSONObject.toJSONString(msgDto));

        } catch (Exception e) {
            logger.info("处理移出群组通知失败，error={}", e);

        }
    }
}
